<?php

namespace app\mall\logic;

use app\data\model\DataUser;
use app\mall_back\model\GoodsLuckyDrawModel;
use app\mall_back\model\TescoCommentModel;
use app\mall_back\model\TescoRecordModel;
use think\facade\Db;
use think\facade\Event;
use think\facade\Log;
use think\helper\Arr;
use Yansongda\Pay\Pay as YansongdaPay;

class orderLogic
{

    /**
     * 预览订单
     *
     * @param int    $uid              用户id
     * @param int    $is_shopping_cart 是否来自购物车 1是 0否
     * @param string $goods_info       商品信息，json数据 例如 {"15":3,"28":7}   [{"id":15,"number":3},{"id":28,"number":7}]
     *
     * @return array
     */
    public function preview_order(int $uid, int $is_shopping_cart, string $goods_info): array
    {
        $goods_info            = json_decode($goods_info, TRUE);
        $goods_arr             = [];
        $goods_total_price     = 0;//商品总价
        $goods_purchase_number = 0;//总购买次数
        foreach ($goods_info as $k => $v) {
            if (empty($v['id']) || empty($v['number'])) return ['code' => 500, 'msg' => '商品信息错误', 'data' => []];
            $goods_arr[$k] = Db::view('one_goods_lucky_draw', 'id ,unit_price ,people_number , participants_number ,is_draw_a_lottery')
                ->where('one_goods_lucky_draw.id', '=', $v['id'])
                ->view('one_goods', 'goods_name ,cover', 'one_goods_lucky_draw.goods_id = one_goods.id')
                ->find();
            if ($v['number'] + $goods_arr[$k]['participants_number'] > $goods_arr[$k]['people_number']) {
                return ['code' => 500, 'msg' => '商品' . $goods_arr[$k]['goods_name'] . '库存不足', 'data' => []];
            }
            if (!empty($goods_arr[$k]['is_draw_a_lottery'])) {
                return ['code' => 500, 'msg' => '商品' . $goods_arr[$k]['goods_name'] . '已经开过奖了', 'data' => []];
            }
            $goods_arr[$k]['purchase_number'] = $v['number'];//购买次数
            $goods_arr[$k]['surplus_number']  = $goods_arr[$k]['people_number'] - $goods_arr[$k]['participants_number'];//剩余次数
            $goods_total_price                += $goods_arr[$k]['unit_price'] * $v['number'];//商品总价
            $goods_purchase_number            += $v['number'];//总购买次数
            if (!empty($is_shopping_cart)) {//如果来自购物车的话清除购物车
                Db::table('one_shopping_cart')
                    ->where([
                        'u_id'                => $uid,
                        'goods_lucky_draw_id' => $v['id']
                    ])->delete();
            }

        }
        return [
            'code' => 200,
            'msg'  => '预览订单',
            'data' => [
                'goods_info'            => $goods_arr,
                'goods_total_price'     => $goods_total_price,
                'goods_purchase_number' => $goods_purchase_number
            ]
        ];
    }

    public function preview_booking(int $id, int $seq_num, int $buy_num)
    {

        $draw = GoodsLuckyDrawModel::find($id);

        $enough = GoodsLuckyDrawModel::where('sequence_no', $draw->sequence_no)
            ->where('sequence_current', '>', $draw->sequence_current)
            ->where('sequence_current', '<=', $draw->sequence_current + $seq_num)
            ->select();

        if ($enough->count() < $seq_num) {
            $this->error('您预购的期数超过了本组抽奖的最大期数！', NULL, 500);
        }

        $total_num    = 0;
        $total_amount = 0.00;
        $bought_draws = [];
        foreach ($enough as $key => $item) {
            if ($item->people_number - $item->participants_number > $buy_num) {
                $num = $buy_num;
            } else {
                $num = $item->people_number - $item->participants_number;
            }

            $sub_amount = bcmul($num, $item->unit_price, 2);

            $item_rows = ['id' => $item->id, 'number' => $num, 'sub_amount' => $sub_amount];

            $fields    = ['sequence_no', 'sequence_total', 'sequence_current', 'unit_price'];
            $item_rows = array_merge($item_rows, Arr::only($item->toArray(), $fields));

            $total_num      += $num;
            $total_amount   = bcadd($total_amount, $sub_amount, 2);
            $bought_draws[] = $item_rows;
        }

        $response                          = [];
        $response['goods_info']            = $bought_draws;
        $response['goods_total_price']     = $total_amount;
        $response['goods_purchase_number'] = $total_num;

        return $response;
    }

    /**
     * 提交支付
     *
     * @param string $goods_info   商品信息，json数据 例如 {"15":3,"28":7}   [{"id":15,"number":3},{"id":28,"number":7}]
     * @param int    $uid          用户id
     * @param int    $coupon_id    优惠券id
     * @param int    $address_id   地址id
     * @param string $pay_password 支付密码
     *
     * @return array
     */
    public function submit_payment(string $goods_info, int $uid, int $coupon_id, int $address_id, string $pay_password): array
    {
        $user = DataUser::mk()->where(['id' => $uid])->find();

//        if ($user['pay_password'] != md5($pay_password)) {
//            return ['code' => 500, 'msg' => '支付密码有误'];
//        }

        if (empty($address_id)) {
            return ['code' => 500, 'msg' => '地址id不能为空'];
        }
        $is_address = Db::table('one_delivery_address')
            ->where([
                ['u_id', '=', $uid],
                ['id', '=', $address_id]
            ])->find();
        if (empty($is_address)) {
            return ['code' => 500, 'msg' => '地址不存在'];
        }

        $goods_info    = json_decode($goods_info, TRUE);
        $total_amount  = 0;//商品总价
        $coupon_amount = 0;//优惠金额
        $tesco_record  = [];//乐购记录
        $sn            = commonLogic::build_order_no();
        $res1          = TRUE;
        Db::startTrans();

        foreach ($goods_info as $k => $v) {
            if (empty($v['id']) || empty($v['number'])) {
                return ['code' => 500, 'msg' => '商品信息错误'];
            }

            $goods_arr[$k] = Db::table('one_goods_lucky_draw', '')
                ->where('id', '=', $v['id'])
                ->field('id, unit_price, people_number, participants_number, is_draw_a_lottery, goods_id')
                ->find();

            if ($v['number'] + $goods_arr[$k]['participants_number'] > $goods_arr[$k]['people_number']) {
                return ['code' => 500, 'msg' => '商品' . $goods_arr[$k]['goods_name'] . '库存不足'];
            }

            if (!empty($goods_arr[$k]['is_draw_a_lottery'])) {
                return ['code' => 500, 'msg' => '商品' . $goods_arr[$k]['goods_name'] . '已经开过奖了'];
            }

            for ($i = 0; $i < $v['number']; $i++) {
                $tesco_record[] = [
                    'u_id'                => $uid,
                    'sn'                  => $sn,
                    'goods_lucky_draw_id' => $v['id'],
                    'goods_id'            => $goods_arr[$k]['goods_id'],
                    'add_ress_id'         => $address_id,
                    'lucky_number'        => $v['id'] . rand(10000, 99999),//幸运号码
                    'consignee'           => $is_address['consignee'],
                    'phone'               => $is_address['phone'],
                    'address'             => $is_address['local_area'] . $is_address['full_address'],
                    'create_time'         => date('Y-m-d H:i:s')
                ];
            }
            $total_amount += $goods_arr[$k]['unit_price'] * $v['number'];//商品总价
            $n            = Db::table('one_goods_lucky_draw')
                ->where('id', '=', $v['id'])
                ->inc('participants_number', $v['number'])
                ->dec('residue_number', $v['number'])
                ->update();//增加参与人数
            if (!$n) {
                $res1 = FALSE;
            }
        }
        $res2 = TRUE;
        if (!empty($coupon_id)) {
            $coupon = Db::table('one_user_coupon')
                ->where([
                    'id'   => $coupon_id,
                    'u_id' => $uid
                ])->find();
            if (empty($coupon) or $coupon['is_use'] == 1) {
                Db::rollback();
                return ['code' => 500, 'msg' => '优惠券不存在或者已经被使用'];
            }
            $coupon_info = Db::table('one_coupon')
                ->where('id', '=', $coupon['coupon_id'])
                ->find();
            if ($coupon_info['satisfy_money'] > $total_amount) {
                Db::rollback();
                return ['code' => 500, 'msg' => '优惠券金额不满足'];
            }
//            $goods_total_price -= $coupon_info['reduce_money'];//商品总价
            $coupon_amount = $coupon_info['reduce_money'];
            $res2          = Db::table('one_user_coupon')
                ->where([
                    'id'   => $coupon_id,
                    'u_id' => $uid
                ])->update(['is_use' => 1]);//将优惠券状态修改为已使用
        }
        $pay_amount = $total_amount - $coupon_amount;
        $user_money = Db::table('one_user_wallet')
            ->where('u_id', '=', $uid)
            ->value('money');//查看用户当前余额
        if ($pay_amount > $user_money) {
            Db::rollback();
            return ['code' => 500, 'msg' => '用户余额不足'];
        }
        //生成乐购订单
        Db::table('one_tesco_order')->insert([
            'sn'           => $sn,
            'u_id'         => $uid,
            'pay_status'   => 1,
            'pay_type'     => 'wallet',
            'goods_info'   => json_encode($goods_info),
            'coupon_id'    => $coupon_id ? $coupon_id : 0,
            'pay_amount'   => $pay_amount,
            'total_amount' => $total_amount,
        ]);


        $res3 = walletLogic::wallet_detailed_add($uid, $pay_amount, 4, 1, 0, 'reduce');//增加记录
        $res4 = Db::table('one_user_wallet')
            ->where('u_id', '=', $uid)
            ->dec('money', $pay_amount)
            ->update();//减少余额
        $res5 = Db::table('one_tesco_record')->insertAll($tesco_record);//添加乐购记录

        //  循环开奖
        $processedVid = [];
        foreach ($goods_info as $k => $v) {
            $draw = GoodsLuckyDrawModel::find($v['id']);

            //  预售订单不开奖
            if ($draw->status == GoodsLuckyDrawModel::STATE_PENDING) {
                continue;
            }

            // 人数到达 并且 没有开奖延迟
            if ($draw['participants_number'] >= $draw['people_number']) {
                if (!in_array($v['id'], $processedVid)) {
                    $processedVid[] = $v['id'];
                    self::run_lottery($v['id']);
                }
            }
        }

        //分销给上级用户积分提成
        if ($user['pid1'] > 1) {
            $commission_rate  = sysdata('commission_rate');//分佣比例%
            $commission_price = bcMath($pay_amount, $commission_rate / 100, '*');
            walletLogic::wallet_detailed_add($user['id'], $commission_price, 7, 2, 0, 'add', '分佣');//增加记录
            Db::table('one_user_wallet')->where('u_id', '=', $user['pid1'])->inc('integral', $commission_price)->update();//增加余额
        }
        //积分返还
        $integral_rate = sysdata('integral_rate');//积分返还手续费比例%
        $back_integral = bcMath($pay_amount, $integral_rate / 100, '*');
        walletLogic::wallet_detailed_add($user['id'], $back_integral, 8, 2, 0, 'add', '积分返还');//增加记录
        Db::table('one_user_wallet')->where('u_id', '=', $user['id'])->inc('integral', $back_integral)->update();//增加余额

        //  检查是否是多期：是多期 并且 本期已完结，尝试开启下期
        $allowStatus = [GoodsLuckyDrawModel::STATE_DRAWING, GoodsLuckyDrawModel::STATE_FINISHED];
        foreach ($goods_info as $k => $v) {
            $draw = GoodsLuckyDrawModel::find($v['id']);
            if ($draw['sequence_total'] <= 1) {
                continue;
            }

            // 预售订单不进此逻辑
            if (in_array($draw['status'], $allowStatus)) {
                $nextDraw = GoodsLuckyDrawModel::where('sequence_no', '=', $draw['sequence_no'])
                    ->where('status', '=', GoodsLuckyDrawModel::STATE_PENDING)
                    ->where('sequence_current', '=',  $draw['sequence_current'] + 1)
                    ->find();
                if ($nextDraw) {
                    $nextDraw->update(['status' => GoodsLuckyDrawModel::STATE_STARTING], ['id' => $nextDraw->id]);
                }
            }
        }

        if ($res1 && $res2 && $res3 && $res4 && $res5) {
            Db::commit();
            return ['code' => 200, 'msg' => '支付成功'];
        }

        Db::rollback();
        return ['code' => 500, 'msg' => '支付失败'];
    }

    /**
     * 提交支付
     *
     * @param string $goods_info 商品信息，json数据 例如 {"15":3,"28":7}   [{"id":15,"number":3},{"id":28,"number":7}]
     * @param int    $uid        用户id
     * @param int    $coupon_id  优惠券id
     * @param int    $address_id 地址id
     * @param string $pey_type   支付方式
     *
     * @return array
     */
    public function submit_payment2(string $goods_info, int $uid, int $coupon_id, int $address_id, string $pay_type): array
    {
        $user = DataUser::mk()->where(['id' => $uid])->find();
        if (empty($address_id)) return ['code' => 500, 'msg' => '地址id不能为空'];
        $is_address = Db::table('one_delivery_address')
            ->where([
                ['u_id', '=', $uid],
                ['id', '=', $address_id]
            ])->find();
        if (empty($is_address)) return ['code' => 500, 'msg' => '地址不存在'];
        $goods_info = json_decode($goods_info, TRUE);
//        var_dump($goods_info);
//        die;
        $total_amount  = 0;//商品总价
        $coupon_amount = 0;//优惠金额
        $tesco_record  = [];//乐购记录
        $sn            = commonLogic::build_order_no();

        foreach ($goods_info as $k => $v) {
            if (empty($v['id']) || empty($v['number'])) return ['code' => 500, 'msg' => '商品信息错误'];
            $goods_arr[$k] = Db::table('one_goods_lucky_draw', '')
                ->where('id', '=', $v['id'])
                ->field('id ,unit_price ,people_number , participants_number ,is_draw_a_lottery,goods_id')
                ->find();
            if ($v['number'] + $goods_arr[$k]['participants_number'] > $goods_arr[$k]['people_number']) {
                return ['code' => 500, 'msg' => '商品' . $goods_arr[$k]['goods_name'] . '库存不足'];
            }
            if (!empty($goods_arr[$k]['is_draw_a_lottery'])) {
                return ['code' => 500, 'msg' => '商品' . $goods_arr[$k]['goods_name'] . '已经开过奖了'];
            }
            $total_amount += $goods_arr[$k]['unit_price'] * $v['number'];//商品总价
        }
        if (!empty($coupon_id)) {
            $coupon = Db::table('one_user_coupon')->where(['id' => $coupon_id, 'u_id' => $uid])->find();
            if (empty($coupon) or $coupon['is_use'] == 1) {
                return ['code' => 500, 'msg' => '优惠券不存在或者已经被使用'];
            }
            $coupon_info = Db::table('one_coupon')->where('id', '=', $coupon['coupon_id'])->find();
            if ($coupon_info['satisfy_money'] > $total_amount) {
                return ['code' => 500, 'msg' => '优惠券金额不满足'];
            }
            $coupon_amount = $coupon_info['reduce_money'];
            Db::table('one_user_coupon')->where(['id' => $coupon_id, 'u_id' => $uid])->update(['is_use' => 1]);//将优惠券状态修改为已使用
        }
        $pay_amount = $total_amount - $coupon_amount;

        //生成乐购订单
        $order = Db::table('one_tesco_order')->insert([
            'sn'           => $sn,
            'u_id'         => $uid,
            'pay_status'   => 0,
            'pay_type'     => $pay_type,
            'goods_info'   => json_encode($goods_info),
            'coupon_id'    => $coupon_id ? $coupon_id : 0,
            'add_ress_id'  => $address_id,
            'pay_amount'   => $pay_amount,
            'total_amount' => $total_amount,
        ]);
        if ($pay_type == 'wechat') {
            $wechatPaymentConfig = config('payment.wechat.default');
            var_dump($wechatPaymentConfig);
            exit;

//            $inst = YansongdaPay::wechat();

        } elseif ($pay_type == 'ali') {
            $config = [
                'app_id'         => '2021003199632503',
                'notify_url'     => 'https://yunwanggou.946260.com/mall/ali_notify',
                'return_url'     => 'https://yunwanggou.946260.com/h5',
                'ali_public_key' => 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuJBANgpkvZKHT/aLO41Oe6t+8gNVz/3SO7zH6v1z1rkSs7tRvIt8UlJNMM5qt4P8ryZqk1kMqpCjV+a+Nku+N9gr29MaJj5v1VwSVlFgl/0edk/c69cOIY6iL9vpncIhZNNt/cUbYSH0Pzb6sc26chiMnR60pEqq4dBiWPUas6DNDxxSXt6ykK3S46VRA1scrxvTwFY4x9ihhKhtlzTROBJTcTy1J2utlP0XjwTCPoKLHRl1CkKu6XwPtKm4KJVRO4XFzfP6YYgoROuW9cs6j1GbQQwOxb5cI65wcXp5W5LJJKstZUNJATEXQvyDlpAbi3+LFex5vAEdfFxn3ZG1eQIDAQAB',
                'private_key'    => 'MIIEpgIBAAKCAQEApBqabBGk+i2EZeL0ETrcad/Lax6g9dWtMnDPYwMd/HNpwisEpFE/szZr82bDo5SlvUZAJhg44Q4fHtLbdT2CK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HMinH2opsnRPWIuA5Ocgh8NcUzcM8A02LZTf3UqOaKjieqhkImyLfY0AnjCiDLov34nQlUKm69AoGBAJjJ02TknN1u9G4GVIn06JFrixIul4NVv3cJf/np0VCNrA9pHcxFAwj828Be+ZD3Q3C/dwkNdsqENQmWojJBv+wzWJeXQOkQTIz/CSgOnrm87TGHDbVQ43QRH18+fRBrBddALyBt25I/IXpYH9Dy/lj8PFXqRW3hDPttr33253vbAoGBAIgxssoHT+TevN+y+gWFABcpzSumW2sf8VNwxn75Hfx+TaE57E4RjBmOTM6iRB2X89sk+jyUOwli1I9nBwunr0XLQnWLEnQvsmIBL5hCJlg59zU7k8VQxHhTNTMnXdb681uFZadqSykDq8VkzOZZNZSAYIwzEXFJ15r2mdtZ9Y+l',
                //                'log' => [ // optional
                //                    'file' => '/logs/alipay.log',
                //                    'level' => 'info', // 建议生产环境等级调整为 info，开发环境为 debug
                //                    'type' => 'single', // optional, 可选 daily.
                //                    'max_file' => 30, // optional, 当 type 为 daily 时有效，默认 30 天
                //                ],
                //                'http' => [ // optional
                //                    'timeout' => 5.0,
                //                    'connect_timeout' => 5.0,
                //                    // 更多配置项请参考 [Guzzle](https://guzzle-cn.readthedocs.io/zh_CN/latest/request-options.html)
                //                ],
                // 'mode' => 'dev', // optional,设置此参数，将进入沙箱模式
            ];
            try {
                // 支付
                $order  = [
                    'out_trade_no' => $sn,
                    'total_amount' => $total_amount,
                    'subject'      => '拼易购',
                ];
                $alipay = YansongdaPay::alipay($config)->wap($order);
//                $pay = $alipay->send();
                Log::info('支付宝响应');
                Log::info($alipay);
                $pay = $alipay->getContent();
            } catch (\Exception $e) {
                echo $e->getMessage(); // 返回自定义的异常信息
            }
//
//            return $pay;
//            var_dump();
//            die;
//            $pay = $pay->getContent();
//            echo 'sadas';
//            $pay = 'aaaaaa';

        } else {
            return ['code' => 500, 'msg' => '支付方式有误'];
        }


        return ['code' => 200, 'msg' => '发起支付', 'pay' => $pay];

    }

    /*
     * 开奖
     * */
    public static function run_lottery($id)
    {
        $goods_lucky_draw = Db::table('one_goods_lucky_draw')->where('id', '=', $id)->find();
        if ($goods_lucky_draw['is_draw_a_lottery'] == 1) {
            return ['code' => 500, 'msg' => '已开过奖'];
        }
        //达到开奖人数
        if ($goods_lucky_draw['participants_number'] >= $goods_lucky_draw['people_number']) {
            //  延时开奖
            if($goods_lucky_draw['draw_delay'] > 0) {
                Db::table('one_goods_lucky_draw')->where('id', '=', $id)
                    ->update(['win_time' => datetime(time()), 'status' => GoodsLuckyDrawModel::STATE_DRAWING, 'up_time' => datetime(time())]);
            } else {
                //有指定中奖用户
                if ($goods_lucky_draw['appoint_phone']) {
                    $user = DataUser::mk()->where(['phone' => $goods_lucky_draw['appoint_phone']])->field('id,nickname,headimg')->find();

                    $TescoRecordModel = new TescoRecordModel();
                    $user_record      = $TescoRecordModel->where(['u_id' => $user['id'], 'goods_lucky_draw_id' => $id])->find();

                    if ($user_record) {
                        $lucky_number_arr = $TescoRecordModel->where(['u_id' => $user['id'], 'goods_lucky_draw_id' => $id])->column('lucky_number');
                        $lucky_number     = array_rand($lucky_number_arr, 1);
//                    var_dump($lucky_number_arr[$lucky_number]);
                        //更新抽奖记录
                        $TescoRecordModel->where(['goods_lucky_draw_id' => $id, 'lucky_number' => $lucky_number_arr[$lucky_number]])->update(['is_win' => 1]);
                        Db::table('one_goods_lucky_draw')->where('id', '=', $id)
                            ->update(['win_time' => datetime(time()), 'is_draw_a_lottery' => 1, 'status' => GoodsLuckyDrawModel::STATE_FINISHED,
                                      'winning_user_id' => $user['id'], 'award_number' => $lucky_number_arr[$lucky_number]]);
                    } else {
                        //没有指定用户购买记录-随机中奖
                        $lucky_number_arr = $TescoRecordModel->where(['goods_lucky_draw_id' => $id])->column('lucky_number');
                        if (empty($lucky_number_arr)) {
                            return ['code' => 500, 'msg' => '还没有人参与竞猜'];
                        }
                        $lucky_number = array_rand($lucky_number_arr, 1);
                        //更新抽奖记录
                        $record         = $TescoRecordModel->where(['goods_lucky_draw_id' => $id, 'lucky_number' => $lucky_number_arr[$lucky_number]])->find();
                        $record->is_win = 1;
                        $record->save();
                        Db::table('one_goods_lucky_draw')->where('id', '=', $id)
                            ->update(['win_time' => datetime(time()), 'is_draw_a_lottery' => 1, 'status' => GoodsLuckyDrawModel::STATE_FINISHED,
                                      'winning_user_id' => $record['u_id'], 'award_number' => $lucky_number_arr[$lucky_number]]);
                    }
                } else {
                    //没有指定中奖用户
                    $TescoRecordModel = new TescoRecordModel();
                    $lucky_number_arr = $TescoRecordModel->where(['goods_lucky_draw_id' => $id])->column('lucky_number');
                    if (empty($lucky_number_arr)) {
                        return ['code' => 500, 'msg' => '还没有人参与竞猜'];
                    }
                    $lucky_number = array_rand($lucky_number_arr, 1);
                    //更新抽奖记录
                    $record         = $TescoRecordModel->where(['goods_lucky_draw_id' => $id, 'lucky_number' => $lucky_number_arr[$lucky_number]])->find();
                    $record->is_win = 1;
                    $record->save();
                    Db::table('one_goods_lucky_draw')->where('id', '=', $id)
                        ->update(['win_time' => datetime(time()), 'is_draw_a_lottery' => 1, 'status' => GoodsLuckyDrawModel::STATE_FINISHED,
                                  'winning_user_id' => $record['u_id'], 'award_number' => $lucky_number_arr[$lucky_number]]);
                }
            }
        }

        Event::trigger('WinningAfter',$id); //中奖后

        return ['code' => 200, 'msg' => '开奖成功'];
    }

    /**
     * 晒单
     *
     * @param int    $uid       用户id
     * @param int    $record_id 记录id
     * @param string $comment   评论
     * @param string $images    图片
     *
     * @return array
     */
    public function comment(int $uid, int $record_id, string $comment, string $images): array
    {
        if (empty($comment)) return ['code' => 500, 'msg' => '内容不能为空'];
        if (empty($images)) return ['code' => 500, 'msg' => '图片不能为空'];

        $TescoRecordModel = new TescoRecordModel();
        $record = $TescoRecordModel->where([
            'u_id'                => $uid,
            'goods_lucky_draw_id' => $record_id,
            'is_win'              => 1,
        ])->find();

        if ($record['is_win'] != 1) {
            return ['code' => 500, 'msg' => '此号码未中奖'];
        }
        if ($record['is_comment'] == 1) {
            return ['code' => 500, 'msg' => '已晒过单'];
        }

        $join_number = $TescoRecordModel->where(['goods_lucky_draw_id' => $record_id, 'u_id' => $uid])->count();
        // 启动事务
        Db::startTrans();
        try {
            //更新记录
            $record->is_comment = 1;
            $record->save();
            //写入评论
            $TescoCommentModel = new TescoCommentModel();
            $TescoCommentModel->save([
                'tesco_record_id' => $record_id,
                'lucky_draw_id'   => $record['goods_lucky_draw_id'],
                'u_id'            => $uid,
                'join_number'     => $join_number,
                'comment'         => $comment,
                'images'          => $images,
            ]);
            // 提交事务
            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
        }
        return ['code' => 200, 'msg' => '晒单成功'];
    }

    /**
     * 最新开奖
     *
     * @param int $page  页数
     * @param int $limit 每页数量
     *
     * @return object
     */
    public function new_record_list(int $page, int $limit): object
    {
        $GoodsLuckyDrawModel = new GoodsLuckyDrawModel();
        $where               = [
            ['status', 'IN', [GoodsLuckyDrawModel::STATE_DRAWING, GoodsLuckyDrawModel::STATE_FINISHED]]
        ];
        $list                = $GoodsLuckyDrawModel->with(['user', 'goods'])
            ->where($where)
            ->orderRaw('win_time DESC, id DESC')
            ->limit(10)
            ->select();

        return $list;
    }

    /**
     * 购买列表
     *
     * @param int $uid    用户id
     * @param int $is_win 是只查获奖记录
     * @param int $page   页数
     * @param int $limit  每页数量
     *
     * @return object
     */
    public function record_list(int $uid, int $state, int $is_win, int $page, int $limit): object
    {
        $where_condition = [
            ['t.u_id', '=', $uid]
        ];
        if ($is_win) {
            if ($is_win == '1') {
                $where_condition[] = ['t.is_win', '=', $is_win];
            }
            if ($is_win == '2') {
                $where_condition[] = ['t.is_win', '=', 0];
            }
        }
        if ($state > 0) {
            switch ($state) {
                case 1:
                    $where_condition[] = ['d.is_draw_a_lottery', '=', 0];
                    break;
                case 2:
                    $where_condition[] = ['d.is_draw_a_lottery', '=', 1];
                    break;
                default:
                    break;
            }
        }
        $TescoRecordModel = new TescoRecordModel();
        $list             = $TescoRecordModel->alias('t')
            ->leftJoin('one_goods_lucky_draw d', 't.goods_lucky_draw_id = d.id')
            ->with(['goods', 'goodsluckydraw'])
            ->field('t.id, t.u_id, t.goods_id, t.goods_lucky_draw_id, d.is_draw_a_lottery')
//            ->field('GROUP_CONCAT(t.`lucky_number`) AS lucky_numbers')
            ->where($where_condition)
            ->group('t.goods_lucky_draw_id')
            ->orderRaw('t.is_win DESC, t.id DESC')
            ->paginate($limit);
        if ($list) {
            foreach ($list as $key => $value) {
                $ldId                   = $value['goods_lucky_draw_id'];
                $join_num               = $TescoRecordModel->where(['u_id' => $uid, 'goods_lucky_draw_id' => $ldId])->count();
                $list[$key]['join_num'] = $join_num;

                $winUid                 = $value['goodsluckydraw']['winning_user_id'];
                $win_user               = DataUser::field('id,phone,headimg,nickname')->find($winUid);
                $list[$key]['win_user'] = $win_user ?: json_decode('{}');
                $list[$key]['is_win']   = intval($uid == $winUid);
                $tmp                    = TescoRecordModel::where(['goods_lucky_draw_id' => $ldId, 'u_id' => $uid])
                    ->column('lucky_number');
                $list[$key]['lucky_numbers'] = implode(',', $tmp);
            }
        }
        return $list;
    }

    /**
     * 晒单记录
     *
     * @param int $uid   用户id
     * @param int $page  页数
     * @param int $limit 每页数量
     *
     * @return object
     */
    public function comment_list(int $uid, int $page, int $limit): object
    {
        $where             = [
            ['u_id', '=', $uid]
        ];
        $TescoCommentModel = new TescoCommentModel();
        $list = $TescoCommentModel->where($where)->with(['commentUser','goodsLuckyDraw.goods'])->paginate($limit);
       // $list              = $TescoCommentModel->where($where)->paginate($limit);
        if ($list) {
            foreach ($list as $key => $value) {
                $list[$key]['images_arr'] = explode('|', $value['images']);
            }
        }
        return $list;
    }

    /*
     * 支付宝回调
     * */
    public function ali_notify(): string
    {
        $config = [
            'app_id'         => '2021003199632503',
            'notify_url'     => 'https://yiyuangou.appldkj.com/mall/ali_notify',
            'return_url'     => 'https://yiyuangou.appldkj.com/h5',
            'ali_public_key' => 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMII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DbscdrT6x0nKdAoGBANzJjh84+wgEog6/uV8+m3iWpEBASnPcEaENv+FTyeL2SZWzD+ZfCF4xy6Q52pIXuAeRLwNncYQiwWqGKcjcvXfxEz+IwvuYuRGVPNhr2FLsxWHt1E5pIyvkOzjQ8iPVQRydPcM9/6FulGDIDsLg0tBlIVwjYv/jooVQufU76yD3AoGBAL5GvfTrH/Iz/gUfCzbdf3WNxYuoCWNqFh5Kr7dtxCDSSk6qm5EyqVjDlI537AkNXXQ8Bzi6hxwKIrt4fYzVwvBvP2orWJnEM839ZLAn9jHXUSOV95/8OpMUURXHNknf1iLyjRsWCCTUGHdnnLB7cN0Zag3WgG+lJJ5EtlLlFNk7AoGBALyjUNSIYKLXIocrc/xWh4seWjOzOmmHK2DJWJnydtl9yB0pInqX05R3QyCLdZ3AujFs8Bged7SH5W1YN7cwMomZ5fIwrTc9o1HMinH2opsnRPWIuA5Ocgh8NcUzcM8A02LZTf3UqOaKjieqhkImyLfY0AnjCiDLov34nQlUKm69AoGBAJjJ02TknN1u9G4GVIn06JFrixIul4NVv3cJf/np0VCNrA9pHcxFAwj828Be+ZD3Q3C/dwkNdsqENQmWojJBv+wzWJeXQOkQTIz/CSgOnrm87TGHDbVQ43QRH18+fRBrBddALyBt25I/IXpYH9Dy/lj8PFXqRW3hDPttr33253vbAoGBAIgxssoHT+TevN+y+gWFABcpzSumW2sf8VNwxn75Hfx+TaE57E4RjBmOTM6iRB2X89sk+jyUOwli1I9nBwunr0XLQnWLEnQvsmIBL5hCJlg59zU7k8VQxHhTNTMnXdb681uFZadqSykDq8VkzOZZNZSAYIwzEXFJ15r2mdtZ9Y+l'
        ];
        Log::info('支付宝支付回调');
        Log::info($_POST);
        $alipay = YansongdaPay::alipay($config);

        try {
            $data = $alipay->verify(); // 是的，验签就这么简单！
            Log::info($data);
            Log::info('支付宝支付回调验签');
            Log::info($data->all());
//            Log::debug('Alipay notify', $data->all());
            // 请自行对 trade_status 进行判断及其它逻辑进行判断，在支付宝的业务通知中，只有交易通知状态为 TRADE_SUCCESS 或 TRADE_FINISHED 时，支付宝才会认定为买家付款成功。
            // 1、商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号；
            // 2、判断total_amount是否确实为该订单的实际金额(即商户订单创建时的金额)；
            // 3、校验通知中的seller_id(或者seller_email) 是否为out_trade_no这笔单据的对应的操作方(有的时候，一个商户可能有多个seller_id/seller_email)；
            // 4、验证app_id是否为该商户本身。
            // 5、其它业务逻辑情况
            $order        = Db::table('one_tesco_order')->where(['sn' => $data['out_trade_no'], 'pay_status' => 0])->find();
            $goods_info   = json_decode($order['goods_info'], TRUE);
            $tesco_record = [];//乐购记录
            $uid          = $order['u_id'];
            $sn           = $order['sn'];
            $address_id   = $order['add_ress_id'];
            $is_address   = Db::table('one_delivery_address')->where([['u_id', '=', $uid], ['id', '=', $address_id]])->find();
            Db::startTrans();

            foreach ($goods_info as $k => $v) {
                $goods_arr[$k] = Db::table('one_goods_lucky_draw', '')
                    ->where('id', '=', $v['id'])
                    ->field('id ,unit_price ,people_number , participants_number ,is_draw_a_lottery,goods_id')
                    ->find();

                for ($i = 0; $i < $v['number']; $i++) {
                    $tesco_record[] = [
                        'u_id'                => $uid,
                        'sn'                  => $sn,
                        'goods_lucky_draw_id' => $v['id'],
                        'goods_id'            => $goods_arr[$k]['goods_id'],
                        'add_ress_id'         => $address_id,
                        'lucky_number'        => $v['id'] . rand(10000, 99999),//幸运号码
                        'consignee'           => $is_address['consignee'],
                        'phone'               => $is_address['phone'],
                        'address'             => $is_address['local_area'] . $is_address['full_address'],
                    ];
                }
                $n = Db::table('one_goods_lucky_draw')
                    ->where('id', '=', $v['id'])
                    ->inc('participants_number', $v['number'])
                    ->dec('residue_number', $v['number'])
                    ->update();//增加参与人数
            }
            $res5 = Db::table('one_tesco_record')->insertAll($tesco_record);//添加乐购记录
            Log::info('添加乐购记录');
            Log::info($res5);
            Log::info($tesco_record);
            $user = DataUser::mk()->where(['id' => $uid])->find();
            //分销给上级用户积分提成
            $pay_amount = $order['pay_amount'];
            if ($user['pid1'] > 1) {
                $commission_rate  = sysdata('commission_rate');//分佣比例%
                $commission_price = bcMath($pay_amount, $commission_rate / 100, '*');
                walletLogic::wallet_detailed_add($user['id'], $commission_price, 7, 2, 0, 'add', '分佣');//增加记录
                Db::table('one_user_wallet')->where('u_id', '=', $user['pid1'])->inc('integral', $commission_price)->update();//增加余额
            }
            //积分返还
            $integral_rate = sysdata('integral_rate');//积分返还手续费比例%
            $back_integral = bcMath($pay_amount, $integral_rate / 100, '*');

            walletLogic::wallet_detailed_add($user['id'], $back_integral, 8, 2, 0, 'add', '积分返还');//增加记录
            Db::table('one_user_wallet')->where('u_id', '=', $user['id'])->inc('integral', $back_integral)->update();//增加余额

//            $order->pay_status = 1;
//            $order->save();
            Db::table('one_tesco_order')->where(['sn' => $data['out_trade_no']])->update(['pay_status' => 1]);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            Log::error('Alipay notify error:' . $e->getMessage());

        }

        return $alipay->success()->send();// laravel 框架中请直接 `return $alipay->success()`

    }

    /**
     * 提交支付
     *
     * @param int    $uid            用户id
     * @param float  $recharge_money 充值金额
     * @param string $pay_type       支付方式
     *
     * @return array
     */
    public function recharge(int $uid, float $recharge_money, string $pay_type): array
    {
        $user = DataUser::mk()->where(['id' => $uid])->find();

        if (floor($recharge_money) != $recharge_money || $recharge_money < 1) {
            return ['code' => 500, 'msg' => '充值金额需大于1正整数'];
        }

        $sn = commonLogic::build_order_no();

        //生成充值订单
        $order = Db::table('one_user_recharge')->insert([
            'sn'             => $sn,
            'u_id'           => $uid,
            'pay_status'     => 0,
            'pay_type'       => $pay_type,
            'recharge_money' => $recharge_money,
            'account_money'  => $recharge_money,
        ]);
        if ($pay_type == 'wechat') {

        } elseif ($pay_type == 'ali') {
            $config = [
                'app_id'         => '2021003199632503',
                'notify_url'     => 'https://yunwanggou.946260.com/mall/ali_recharge_notify',
                'return_url'     => 'https://yunwanggou.946260.com/h5',
                'ali_public_key'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vLaPdFYoluQZCJBkaCJI77p+0HuY7GUuiXdYLFMEDbscdrT6x0nKdAoGBANzJjh84+wgEog6/uV8+m3iWpEBASnPcEaENv+FTyeL2SZWzD+ZfCF4xy6Q52pIXuAeRLwNncYQiwWqGKcjcvXfxEz+IwvuYuRGVPNhr2FLsxWHt1E5pIyvkOzjQ8iPVQRydPcM9/6FulGDIDsLg0tBlIVwjYv/jooVQufU76yD3AoGBAL5GvfTrH/Iz/gUfCzbdf3WNxYuoCWNqFh5Kr7dtxCDSSk6qm5EyqVjDlI537AkNXXQ8Bzi6hxwKIrt4fYzVwvBvP2orWJnEM839ZLAn9jHXUSOV95/8OpMUURXHNknf1iLyjRsWCCTUGHdnnLB7cN0Zag3WgG+lJJ5EtlLlFNk7AoGBALyjUNSIYKLXIocrc/xWh4seWjOzOmmHK2DJWJnydtl9yB0pInqX05R3QyCLdZ3AujFs8Bged7SH5W1YN7cwMomZ5fIwrTc9o1HMinH2opsnRPWIuA5Ocgh8NcUzcM8A02LZTf3UqOaKjieqhkImyLfY0AnjCiDLov34nQlUKm69AoGBAJjJ02TknN1u9G4GVIn06JFrixIul4NVv3cJf/np0VCNrA9pHcxFAwj828Be+ZD3Q3C/dwkNdsqENQmWojJBv+wzWJeXQOkQTIz/CSgOnrm87TGHDbVQ43QRH18+fRBrBddALyBt25I/IXpYH9Dy/lj8PFXqRW3hDPttr33253vbAoGBAIgxssoHT+TevN+y+gWFABcpzSumW2sf8VNwxn75Hfx+TaE57E4RjBmOTM6iRB2X89sk+jyUOwli1I9nBwunr0XLQnWLEnQvsmIBL5hCJlg59zU7k8VQxHhTNTMnXdb681uFZadqSykDq8VkzOZZNZSAYIwzEXFJ15r2mdtZ9Y+l',
                //                'log' => [ // optional
                //                    'file' => '/logs/alipay.log',
                //                    'level' => 'info', // 建议生产环境等级调整为 info，开发环境为 debug
                //                    'type' => 'single', // optional, 可选 daily.
                //                    'max_file' => 30, // optional, 当 type 为 daily 时有效，默认 30 天
                //                ],
                //                'http' => [ // optional
                //                    'timeout' => 5.0,
                //                    'connect_timeout' => 5.0,
                //                    // 更多配置项请参考 [Guzzle](https://guzzle-cn.readthedocs.io/zh_CN/latest/request-options.html)
                //                ],
                // 'mode' => 'dev', // optional,设置此参数，将进入沙箱模式
            ];
            try {
                // 支付
                $order  = [
                    'out_trade_no' => $sn,
                    'total_amount' => $recharge_money,
                    'subject'      => '拼易购',
                ];
                $alipay = YansongdaPay::alipay($config)->wap($order);
//                $pay = $alipay->send();
                Log::info('支付宝响应');
                Log::info($alipay);
                $pay = $alipay->getContent();
            } catch (\Exception $e) {
                echo $e->getMessage(); // 返回自定义的异常信息
            }


        } else {
            return ['code' => 500, 'msg' => '支付方式有误'];
        }


        return ['code' => 200, 'msg' => '发起支付', 'pay' => $pay];

    }

    /*
     * 支付宝充值回调
     * */
    public function ali_recharge_notify(): string
    {
        $config = [
            'app_id'         => '2021003199632503',
            'notify_url'     => 'https://yiyuangou.appldkj.com/mall/ali_recharge_notify',
            'return_url'     => 'https://yiyuangou.appldkj.com/h5',
            'ali_public_key' => 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuJBANgpkvZKHT/aLO41Oe6t+8gNVz/3SO7zH6v1z1rkSs7tRvIt8UlJNMM5qt4P8ryZqk1kMqpCjV+a+Nku+N9gr29MaJj5v1VwSVlFgl/0edk/c69cOIY6iL9vpncIhZNNt/cUbYSH0Pzb6sc26chiMnR60pEqq4dBiWPUas6DNDxxSXt6ykK3S46VRA1scrxvTwFY4x9ihhKhtlzTROBJTcTy1J2utlP0XjwTCPoKLHRl1CkKu6XwPtKm4KJVRO4XFzfP6YYgoROuW9cs6j1GbQQwOxb5cI65wcXp5W5LJJKstZUNJATEXQvyDlpAbi3+LFex5vAEdfFxn3ZG1eQIDAQAB',
            'private_key'    => 'MIIEpgIBAAKCAQEApBqabBGk+i2EZeL0ETrcad/Lax6g9dWtMnDPYwMd/HNpwisEpFE/szZr82bDo5SlvUZAJhg44Q4fH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IwrTc9o1HMinH2opsnRPWIuA5Ocgh8NcUzcM8A02LZTf3UqOaKjieqhkImyLfY0AnjCiDLov34nQlUKm69AoGBAJjJ02TknN1u9G4GVIn06JFrixIul4NVv3cJf/np0VCNrA9pHcxFAwj828Be+ZD3Q3C/dwkNdsqENQmWojJBv+wzWJeXQOkQTIz/CSgOnrm87TGHDbVQ43QRH18+fRBrBddALyBt25I/IXpYH9Dy/lj8PFXqRW3hDPttr33253vbAoGBAIgxssoHT+TevN+y+gWFABcpzSumW2sf8VNwxn75Hfx+TaE57E4RjBmOTM6iRB2X89sk+jyUOwli1I9nBwunr0XLQnWLEnQvsmIBL5hCJlg59zU7k8VQxHhTNTMnXdb681uFZadqSykDq8VkzOZZNZSAYIwzEXFJ15r2mdtZ9Y+l'
        ];
        Log::info('支付宝充值回调');
        Log::info($_POST);
        $alipay = YansongdaPay::alipay($config);

        try {
            $data = $alipay->verify(); // 是的，验签就这么简单！
            Log::info($data);
            Log::info('支付宝充值回调验签');
            Log::info($data->all());
//            Log::debug('Alipay notify', $data->all());
            // 请自行对 trade_status 进行判断及其它逻辑进行判断，在支付宝的业务通知中，只有交易通知状态为 TRADE_SUCCESS 或 TRADE_FINISHED 时，支付宝才会认定为买家付款成功。
            // 1、商户需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号；
            // 2、判断total_amount是否确实为该订单的实际金额(即商户订单创建时的金额)；
            // 3、校验通知中的seller_id(或者seller_email) 是否为out_trade_no这笔单据的对应的操作方(有的时候，一个商户可能有多个seller_id/seller_email)；
            // 4、验证app_id是否为该商户本身。
            // 5、其它业务逻辑情况
            $order = Db::table('one_user_recharge')->where(['sn' => $data['out_trade_no'], 'pay_status' => 0])->find();
            $uid   = $order['u_id'];
            $sn    = $order['sn'];
            $user  = DataUser::mk()->where(['id' => $uid])->find();
            Db::startTrans();

            $account_money = $order['account_money'];

            $memo = '充值:' . $order['sn'];
            walletLogic::wallet_detailed_add($user['id'], $account_money, 1, 1, 0, 'add', $memo);//增加记录
            Db::table('one_user_wallet')->where('u_id', '=', $user['id'])->inc('money', $account_money)->update();//增加余额
            Db::table('one_user_recharge')->where(['sn' => $data['out_trade_no']])->update(['pay_status' => 1]);

            Event::trigger('UserRechargeSuccess',$order);

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            Log::error('Alipay recharge notify error:' . $e->getMessage());

        }

        return $alipay->success()->send();// laravel 框架中请直接 `return $alipay->success()`

    }

    /**
     * 超时订单取消
     */
    public function auto_cancle()
    {
        $now   = datetime(time() - 300);
        $where = [
            ['pay_status', '=', 0],
            ['create_time', '<', $now],
        ];

        $list = Db::table('one_tesco_order')->where($where)->select();
//        var_dump($list);
        if ($list) {
            foreach ($list as $key => $value) {
                if ($value['coupon_id'] > 0) {
                    //回退优惠券
                    Db::table('one_user_coupon')->where([
                        'id' => $value['coupon_id']
                    ])->update(['is_use' => 0]);//将优惠券状态修改为未使用
                }
                Db::table('one_tesco_order')->where(['id' => $value['id']])->update(['pay_status' => 2]);
            }
        }

    }


}